package com.bdqn.base.logger;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * WebLoggerAspect
 *
 * @author LILIBO
 */
@Aspect
@Slf4j
@Component
public class WebLoggerAspect {

    private static StringBuffer sb = new StringBuffer();

    /**
     * 切点（以自定义注解@WebLogger为切点）
     */
    @Pointcut("@annotation(com.bdqn.base.logger.WebLogger)")
    public void WebLogger() {
    }

    /**
     * 在切点之前植入
     */
    @Before("WebLogger()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 开始打印请求日志
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 获得Request请求
        HttpServletRequest request = attributes.getRequest();

        // 获取@WebLogger注解的描述信息
        String loggerDescription = getAspectLogValue(joinPoint);

        // 打印请求相关参数
        // StringBuffer sb = new StringBuffer();
        sb.append("\n------------------------------------------------------------------------------------------------");
        // 打印请求 url
        sb.append("\n--> Request URL    : ").append(request.getRequestURL().toString());
        // 打印描述信息
        sb.append("\n--> Description    : ").append(loggerDescription);
        // 打印 Http method
        sb.append("\n--> HTTP Method    : ").append(request.getMethod());
        // 打印调用Controller的全路径以及执行方法
        sb.append("\n--> Class Method   : ").append(joinPoint.getSignature().getDeclaringTypeName()).append(".").append(joinPoint.getSignature().getName());
        // 打印请求的 IP
        sb.append("\n--> IP Address     : ").append(request.getRemoteAddr());
        // 打印请求入参
        String args = "";
        try {
            args = JSON.toJSONString(joinPoint.getArgs());
        } catch (Exception e) {
            args = "-";
        }
        sb.append("\n--> Request Args   : ").append(args);

        sb.append("\n"); // 换行，前面是请求信息，后面是响应信息
    }

    /**
     * 在切点之后植入
     */
    @After("WebLogger()")
    public void doAfter() throws Throwable {
        // 接口结束后
    }

    /**
     * 环绕通知
     */
    @Around("WebLogger()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        // 记录执行开始时间
        long startTime = System.currentTimeMillis();

        // 执行被代理的原方法
        Object result = proceedingJoinPoint.proceed();

        // 打印响应参数
        sb.append("\n<-- Response Body  : ").append(JSON.toJSONString(result));
        // 执行耗时
        sb.append("\n<-- Time Consuming : ").append(System.currentTimeMillis() - startTime).append(" ms");
        sb.append("\n------------------------------------------------------------------------------------------------");
        // 打印日志，WebLoggerAspect的Debug日志在配置中开启
        log.debug(sb.toString());
        sb.setLength(0); // 清空
        return result;
    }

    /**
     * 获取切面注解的描述
     *
     * @return 描述信息
     */
    public String getAspectLogValue(JoinPoint joinPoint) throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        StringBuilder description = new StringBuilder("");
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazz = method.getParameterTypes();
                if (clazz.length == arguments.length) {
                    description.append(method.getAnnotation(WebLogger.class).value());
                    break;
                }
            }
        }
        return description.toString();
    }

}

